// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;
using System.Collections.Concurrent;

namespace SnapObjects.Data
{
    internal class ModelMetaManager
    {
        protected static readonly ConcurrentDictionary<Type, PocoModelMeta> _metadatas
                = new ConcurrentDictionary<Type, PocoModelMeta>();

       public static bool UseDefaultValueConverter { get; set; }

        public static PocoModelMeta GetModelMeta(Type modelType)
        {
            if (!_metadatas.TryGetValue(modelType, out var meta))
            {
                meta = new PocoModelMeta(modelType);

                _metadatas.TryAdd(modelType, meta);

                CreateValueConverter(meta);
            }

            return meta;
        }

        private static void CreateValueConverter(IPocoModelMeta modelMeta)
        {
            if (UseDefaultValueConverter)
            {
                foreach (var property in modelMeta.PropertyMap)
                {
                    if (!property.Value.HasConversion)
                    {
                        property.Value.HasConversion = true;
                        property.Value.ValueConverter = new DefaultValueConverter(property.Value.DataType);
                    }
                }
            }
        }
    }
}
